import pymongo
from selenium import webdriver
import time

def isExist(ele_list):
    if(len(ele_list) == 0):
        return False
    return True

myclient = pymongo.MongoClient('mongodb://47.93.220.108:27017/')
mydb = myclient['movie']
res = set()
for item in mydb.movieComment.find():
    name = item['movie_director']
    res.add(name)

driver = webdriver.Chrome(executable_path='/Users/aaa/py/chromedriver')

for i in res:
    driver.get('https://search.douban.com/movie/subject_search?search_text='+i)
    time.sleep(1)
    rank = 0
    #判断是否有结果
    if(not isExist(driver.find_elements_by_xpath('//div[@class="title"]/a'))):
        rank = 5.0
        print('无结果')
    else :
        driver.find_element_by_xpath('//div[@class="title"]/a').click()
        time.sleep(1)
        best_scores = driver.find_elements_by_xpath("//div[@id='best_movies']//em")
        if(isExist(best_scores)):
            for best_score in best_scores:
                rank += float(best_score.text if best_score.text != '' else 5.0)
            rank = rank/len(best_scores)
        else:
            rank = 5.0
    rank = round(rank,2)
    print(rank)
    data = {
        'name' : i,
        'rank' : rank
    }

    mydb.director.insert_one(data)
    
    

